﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WeixinPayResdk.Helper
{
    /// <summary>
    /// 读取私钥、证书
    /// </summary>
    public abstract class ReadFile
    {
        /// <summary>
        /// 读取应用私钥
        /// </summary>
        /// <param name="clientKeyFilePath">物理路径</param>
        /// <param name="removeHeadFooter">是否去除头尾等干扰文本，一般为true</param>
        /// <returns></returns>
        public static string APIClientKey(string clientKeyFilePath, bool removeHeadFooter=true)
        {
            if (!File.Exists(clientKeyFilePath))
            {
                throw new FileNotFoundException("clientKeyFilePath Not Found");
            }
            string privateKey = File.ReadAllText(clientKeyFilePath);

            if (removeHeadFooter) 
            {
                privateKey = privateKey.Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "").Replace("\n", "").Replace("\r", "");
            }

            return privateKey;
        }

        /// <summary>
        /// 读取微信证书（无用，具体参考以下链接）
        /// https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay7_0.shtml
        /// </summary>
        /// <param name="clientCertFilePath">物理路径</param>
        /// <param name="removeHeadFooter">是否去除头尾等干扰文本</param>
        public static string APIClientCert(string clientCertFilePath, bool removeHeadFooter = false)
        {
            if (!File.Exists(clientCertFilePath))
            {
                throw new FileNotFoundException("clientCertFilePath Not Found");
            }
            string clientCert = File.ReadAllText(clientCertFilePath);

            if (removeHeadFooter)
            {
                clientCert = clientCert.Replace("-----BEGIN CERTIFICATE-----", "").Replace("-----END CERTIFICATE-----", "").Replace("\n", "").Replace("\r", "");
            }

            return clientCert;
        }
    }
}
